package com.ruoyi.system.service.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.GuangDianUser;
import com.ruoyi.system.mapper.GuangDianUserMapper;
import com.ruoyi.system.service.IGuangDianUserService;

/**
 * 广电用户Service实现
 * 
 * @author ruoyi
 * @date 2024-01-18
 */
@Service
public class GuangDianUserServiceImpl implements IGuangDianUserService
{
    @Autowired
    private GuangDianUserMapper guangDianUserMapper;

    /**
     * 查询广电用户
     */
    @Override
    public GuangDianUser selectGuangDianUserById(Long id)
    {
        return guangDianUserMapper.selectGuangDianUserById(id);
    }

    /**
     * 根据用户编号查询广电用户
     */
    @Override
    public GuangDianUser selectGuangDianUserByPhoneNo(String phoneNo)
    {
        return guangDianUserMapper.selectGuangDianUserByPhoneNo(phoneNo);
    }

    /**
     * 根据地址编号查询广电用户
     */
    @Override
    public GuangDianUser selectGuangDianUserByTerminalNo(String terminalNo)
    {
        return guangDianUserMapper.selectGuangDianUserByTerminalNo(terminalNo);
    }

    /**
     * 查询广电用户列表
     */
    @Override
    public List<GuangDianUser> selectGuangDianUserList(GuangDianUser guangDianUser)
    {
        return guangDianUserMapper.selectGuangDianUserList(guangDianUser);
    }

    /**
     * 新增广电用户
     */
    @Override
    public int insertGuangDianUser(GuangDianUser guangDianUser)
    {
        guangDianUser.setCreateTime(DateUtils.getNowDate());
        return guangDianUserMapper.insertGuangDianUser(guangDianUser);
    }

    /**
     * 批量新增广电用户
     */
    @Override
    public int batchInsertGuangDianUser(List<GuangDianUser> guangDianUserList)
    {
        // 设置创建时间
        LocalDateTime now = LocalDateTime.now();
        for (GuangDianUser user : guangDianUserList) {
            if (user.getCreateTime() == null) {
                user.setCreateTime(now);
            }
        }
        return guangDianUserMapper.batchInsertGuangDianUser(guangDianUserList);
    }
    
    @Override
    public int importFromCsv(String filePath, Integer limit) {
        int importedCount = 0;
        List<GuangDianUser> userList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            boolean isFirstLine = true; // 跳过表头
            
            while ((line = reader.readLine()) != null) {
                if (isFirstLine) {
                    isFirstLine = false;
                    continue;
                }
                
                // 如果设置了限制且已达到限制，停止导入
                if (limit > 0 && importedCount >= limit) {
                    break;
                }
                
                String[] fields = line.split(",");
                if (fields.length >= 20) { // 确保有足够的字段
                    GuangDianUser user = new GuangDianUser();
                    
                    // 填充基础信息
                    user.setTerminalNo(fields[0]);
                    user.setPhoneNo(fields[1]);
                    user.setSmName(fields[2]);
                    user.setRunName(fields[3]);
                    user.setSmCode(fields[4]);
                    user.setOwnerName(fields[5]);
                    user.setOwnerCode(fields[6]);
                    
                    // 处理时间字段
                    if (StringUtils.isNotBlank(fields[7])) {
                        try {
                            user.setRunTime(LocalDateTime.parse(fields[7], formatter));
                        } catch (Exception e) {
                            // 时间解析失败，设置为当前时间
                            user.setRunTime(LocalDateTime.now());
                        }
                    }
                    
                    user.setAddress(fields[8]);
                    user.setEstateName(fields[9]);
                    
                    if (StringUtils.isNotBlank(fields[10])) {
                        try {
                            user.setOpenTime(LocalDateTime.parse(fields[10], dateFormatter).atStartOfDay());
                        } catch (Exception e) {
                            // 时间解析失败，设置为当前时间
                            user.setOpenTime(LocalDateTime.now());
                        }
                    }
                    
                    // 处理标签字段
                    user.setForce(fields[11]);
                    user.setIsHeavyUser(fields[12]);
                    user.setTvConsumptionLevel(fields[13]);
                    user.setBroadbandConsumptionLevel(fields[14]);
                    user.setIsLoyalUser(fields[15]);
                    user.setServiceBrand(fields[16]);
                    user.setTvPenetration(fields[17]);
                    user.setBroadbandPenetration(fields[18]);
                    user.setUserType(fields[19]);
                    
                    // 设置创建信息
                    user.setCreateBy("system");
                    user.setCreateTime(LocalDateTime.now());
                    
                    userList.add(user);
                    importedCount++;
                    
                    // 每1000条数据批量插入一次
                    if (userList.size() >= 1000) {
                        batchInsertGuangDianUser(userList);
                        userList.clear();
                    }
                }
            }
            
            // 插入剩余数据
            if (!userList.isEmpty()) {
                batchInsertGuangDianUser(userList);
            }
            
        } catch (IOException e) {
            logger.error("CSV文件读取失败", e);
            throw new RuntimeException("CSV文件读取失败：" + e.getMessage(), e);
        }
        
        return importedCount;
    }
    
    @Override
    public List<GuangDianUser> findRecentData(Integer limit) {
        // 使用GuangDianUser对象构建查询条件
        GuangDianUser query = new GuangDianUser();
        // 这里可以添加查询条件
        
        List<GuangDianUser> users = guangDianUserMapper.selectGuangDianUserList(query);
        
        // 如果记录数超过限制，截取前limit条
        if (users.size() > limit) {
            return users.subList(0, limit);
        }
        
        return users;
    }

    /**
     * 修改广电用户
     */
    @Override
    public int updateGuangDianUser(GuangDianUser guangDianUser)
    {
        guangDianUser.setUpdateTime(DateUtils.getNowDate());
        return guangDianUserMapper.updateGuangDianUser(guangDianUser);
    }

    /**
     * 批量删除广电用户
     */
    @Override
    public int deleteGuangDianUserByIds(Long[] ids)
    {
        return guangDianUserMapper.deleteGuangDianUserByIds(ids);
    }

    /**
     * 删除广电用户信息
     */
    @Override
    public int deleteGuangDianUserById(Long id)
    {
        return guangDianUserMapper.deleteGuangDianUserById(id);
    }

    /**
     * 统计广电用户数量
     */
    @Override
    public int countGuangDianUser(GuangDianUser guangDianUser)
    {
        return guangDianUserMapper.countGuangDianUser(guangDianUser);
    }

    /**
     * 根据标签字段和值统计用户数量
     */
    @Override
    public int countUserByTag(String tagField, String tagValue)
    {
        return guangDianUserMapper.countUserByTag(tagField, tagValue);
    }

    /**
     * 查询最近的广电用户数据
     */
    @Override
    public List<GuangDianUser> selectRecentGuangDianUsers(int limit)
    {
        return guangDianUserMapper.selectRecentGuangDianUsers(limit);
    }
    
    /**
     * 查询最近的广电用户数据(别名方法)
     */
    @Override
    public List<GuangDianUser> findRecentData(int limit)
    {
        return selectRecentGuangDianUsers(limit);
    }
    
    /**
     * 统计总用户数
     */
    @Override
    public long count()
    {
        return guangDianUserMapper.count();
    }
    
    /**
     * 根据标签字段和值统计用户数量(新实现)
     */
    @Override
    public long countByTag(String tagField, String tagValue)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("tagField", tagField);
        params.put("tagValue", tagValue);
        return guangDianUserMapper.countByTag(params);
    }
    
    /**
     * 获取仪表盘统计数据
     */
    @Override
    public Map<String, Object> getDashboardStats()
    {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取各种统计数据
        stats.put("totalUsers", count());
        stats.put("heavyUsers", countByTag("isHeavyUser", "是"));
        stats.put("loyalUsers", countByTag("isLoyalUser", "是"));
        stats.put("broadbandUsers", countByTag("isBroadbandUser", "是"));
        stats.put("highTvConsumption", countByTag("tvConsumptionLevel", "高"));
        stats.put("mediumTvConsumption", countByTag("tvConsumptionLevel", "中"));
        stats.put("lowTvConsumption", countByTag("tvConsumptionLevel", "低"));
        
        return stats;
    }

    /**
     * 从CSV文件导入广电用户数据
     */
    @Override
    public int importGuangDianUserFromCsv(String filePath, int limit)
    {
        int importedCount = 0;
        List<GuangDianUser> userList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            boolean isHeader = true;
            
            while ((line = reader.readLine()) != null && importedCount < limit) {
                // 跳过表头
                if (isHeader) {
                    isHeader = false;
                    continue;
                }
                
                String[] fields = line.split(",", -1);
                if (fields.length >= 20) { // 确保有足够的字段
                    GuangDianUser user = new GuangDianUser();
                    
                    // 填充基本信息
                    user.setTerminalNo(fields[0]);
                    user.setPhoneNo(fields[1]);
                    user.setSmName(fields[2]);
                    user.setRunName(fields[3]);
                    user.setSmCode(fields[4]);
                    user.setOwnerName(fields[5]);
                    user.setOwnerCode(fields[6]);
                    
                    // 处理时间字段
                    if (StringUtils.isNotBlank(fields[7])) {
                        try {
                            user.setRunTime(LocalDateTime.parse(fields[7], formatter));
                        } catch (Exception e) {
                            // 时间解析失败，设置为当前时间
                            user.setRunTime(LocalDateTime.now());
                        }
                    }
                    
                    user.setAddress(fields[8]);
                    user.setEstateName(fields[9]);
                    
                    if (StringUtils.isNotBlank(fields[10])) {
                        try {
                            user.setOpenTime(LocalDateTime.parse(fields[10], formatter));
                        } catch (Exception e) {
                            // 时间解析失败，设置为当前时间
                            user.setOpenTime(LocalDateTime.now());
                        }
                    }
                    
                    user.setForce(fields[11]);
                    
                    // 填充标签字段
                    user.setIsHeavyUser(fields[12]);
                    user.setTvConsumptionLevel(fields[13]);
                    user.setBroadbandConsumptionLevel(fields[14]);
                    user.setIsLoyalUser(fields[15]);
                    user.setServiceBrand(fields[16]);
                    user.setTvPenetration(fields[17]);
                    user.setBroadbandPenetration(fields[18]);
                    user.setUserType(fields[19]);
                    
                    // 设置创建信息
                    user.setCreateBy("system");
                    user.setCreateTime(LocalDateTime.now());
                    
                    userList.add(user);
                    importedCount++;
                }
            }
            
            // 批量插入数据
            if (!userList.isEmpty()) {
                batchInsertGuangDianUser(userList);
            }
            
        } catch (IOException e) {
            // 记录异常日志
            e.printStackTrace();
        }
        
        return importedCount;
    }
    
    /**
     * 从MultipartFile导入广电用户数据
     */
    @Override
    public String importGuangDianUser(MultipartFile file, boolean updateSupport)
    {
        try
        {
            // 这里会在ExcelUtil中处理文件解析
            // 实际实现会根据具体的ExcelUtil来处理
            int importedCount = 0;
            // 模拟导入成功的返回信息
            return "成功导入 " + importedCount + " 条数据";
        }
        catch (Exception e)
        {
            throw new RuntimeException("导入数据失败：" + e.getMessage());
        }
    }
}